package cn.smile.utils;

import cn.smile.commons.constant.MailConstant;
import org.apache.commons.codec.CharEncoding;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

/**
 * @author smile-jt
 * 邮件发送
 */
public class SendMailUtil {

    /**
     * 发送邮件
     *
     * @param receiveAdd 接收邮件邮箱地址
     * @param title      邮件标题
     * @param content    邮件内容
     */
    @SuppressWarnings("ExtractMethodRecommender")
    public static void sendEmail(String receiveAdd, String title, String content) throws Exception {
        //1.创建连接对象
        Properties properties = new Properties();
        //1.2 设置发送邮件的服务器
        properties.put(MailConstant.EMAIL_HOST_KEY, MailConstant.EMAIL_HOST);
        //1.3 需要经过授权,用户名和密码的校验(必须)
        properties.put(MailConstant.EMAIL_AUTH_KEY, Boolean.TRUE);
        properties.put(MailConstant.EMAIL_SMTP_SSL_KEY, Boolean.TRUE);
        properties.put(MailConstant.EMAIL_PROTOCOLS_KEY, MailConstant.EMAIL_PROTOCOLS);
        //1.4 默认以 25 端口发送
        properties.setProperty(MailConstant.EMAIL_SOCKET_FACTORY_KEY, MailConstant.EMAIL_SOCKET_FACTORY);
        properties.setProperty(MailConstant.EMAIL_FALLBACK_KEY, MailConstant.EMAIL_FALLBACK);
        properties.setProperty(MailConstant.EMAIL_PORT_KEY, MailConstant.EMAIL_PORT);
        properties.setProperty(MailConstant.EMAIL_SOCKET_FACTORY_PORT_KEY, MailConstant.EMAIL_SOCKET_FACTORY_PORT);
        //1.5 认证信息
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MailConstant.ACCOUNT, MailConstant.PASSWORD);
            }
        });
        //2.创建邮件对象
        Message message = new MimeMessage(session);
        //2.1设置发件人
        message.setFrom(new InternetAddress(MailConstant.ACCOUNT, MailConstant.SERVER_PERSONAL_NAME, CharEncoding.UTF_8));
        //2.2设置收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receiveAdd));
        //2.3设置抄送者(PS:没有这一条网易会认为这是一条垃圾短信，而发不出去)
        message.setRecipient(Message.RecipientType.CC, new InternetAddress(MailConstant.ACCOUNT));
        //2.4设置邮件的主题
        message.setSubject(title);
        //2.5设置邮件的内容
        message.setContent(content, MailConstant.EMAIL_TYPE_FORMAT);

        //3.发送邮件
        Transport.send(message);
    }
}